package org.example.demo.apiv2.sql;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.select.Join;
import org.example.demo.apiv2.constant.CommonConstant;
import org.example.demo.apiv2.constant.JoinType;
import org.example.demo.apiv2.entity.ExpressionEntity;
import org.example.demo.apiv2.entity.JoinEntity;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class JoinParser {

    /**
     * 构造jsqlparser的Join对象
     *
     * @param joinEntity
     * @return
     */
    public static Join getJoin(JoinEntity joinEntity) {
        Join join = new Join();
        Table joinTable = TableParser.getTable(joinEntity.getTable(), joinEntity.getTableAlias(), CommonConstant.useAs);
        join.setRightItem(joinTable);
        String joinType = joinEntity.getType();
        switch (joinType) {
            case JoinType.INNER_JOIN:
                join.setInner(true);
                break;
            case JoinType.LEFT_JOIN:
                join.setLeft(true);
                break;
            case JoinType.RIGHT_JOIN:
                join.setRight(true);
                break;
            case JoinType.FULL_JOIN:
                join.setFull(true);
                break;
            default:
                log.error("不支持的联接方式: {}", joinType);
                throw new IllegalArgumentException("不支持的联接方式: " + joinType);
        }
        List<ExpressionEntity> expressions = joinEntity.getExpressions();
        Expression onExpression = ExpressionParser.getFilterExpression(expressions);
        join.addOnExpression(onExpression);
        return join;
    }

    /**
     * 构造jsqlparser的Join对象集合
     *
     * @param joinEntityList
     * @return
     */
    public static List<Join> getJoinList(List<JoinEntity> joinEntityList) {
        if (CollectionUtil.isEmpty(joinEntityList)) {
            return new ArrayList<>();
        }
        List<Join> joinList = new ArrayList<>();
        for (JoinEntity joinEntity : joinEntityList) {
            Join join = getJoin(joinEntity);
            joinList.add(join);
        }
        return joinList;
    }
}
